#!/usr/bin/env python
# -*- coding: utf8 -*-
# minifier.py: CSS and JS minifier

__author__ = "Leandro Resende Mattioli <leandro.mattioli@gmail.com>"

import sys
import os
import os.path
import re
from jsmin import *

class Minifier(object):
    """Abstract class for a minifier"""
    def __init__(self):
        self.source_files = []
        self.target_file = ""

    def add_sources_by_dir(self, dir, extension):
        """Chooses all files with <extension> in <dir> as source files"""
        try:
            files = os.listdir(dir)
        except OSError:
            print "Directory %s does not exists!" % dir
            return False
        pattern = r".*\.%s$" % extension
        sources = [os.path.join(dir,f) for f in files if re.match(pattern, f)]
        self.source_files = sources
        return True

    def add_source(self, dir, file):
        """Adds the source file with path <dir>+<file>"""
        self.source_files.append(os.path.join(dir,file))

    def minify(self):
        """Minify source files outputting to <target_file>"""
        pass

class CSSMinifier(Minifier):
    """CSS Minifier, using csstidy utility"""
    def __init__(self):
        Minifier.__init__(self)
        self.csstidy_params = [
            "--compress_colors=true",
            "--compress_font=true",
            "--lowercase_s=true",
            "--remove_bslash=true",
            "--remove_last_\;=true",
            "--sort_properties=true"
            "--sort-selectors=false",
            "--template=high"
        ]

    def minify(self):
        """Minify CSS source files outputting to <target_file>"""
        if self.source_files and self.target_file:
            css = ""
            for f in self.source_files:
                css += open(f).read()
            params = " ".join(self.csstidy_params)
            outfile = self.target_file
            command = "echo \"%s\" | csstidy - %s %s" % (css, params, outfile)
            self.__init__()
            return os.system(command)
        else:
            return False



class JSMinifier(Minifier):
    """Javascript Minifier, using jsmin module"""
    def __init__(self):
        Minifier.__init__(self)

    def minify(self):
        if self.source_files and self.target_file:
            content = ""
            for f in self.source_files:
                content += open(f).read()
            try:
                open(self.target_file, "w").write(jsmin(content))
                result = True
            except IOError:
                result = False
            finally:
                self.__init__()
                return result
        else:
            return False
